<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="98px">
      <el-form-item label="发布人昵称" prop="publisher">
        <el-input
          v-model="queryParams.publisher"
          placeholder="请输入发布人昵称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="内容" prop="content">
        <el-input
          v-model="queryParams.content"
          placeholder="请输入内容"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['campus:post:add']"
        >发布</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['campus:post:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['campus:post:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['campus:post:export']"
        >导出</el-button>
      </el-col> -->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="postList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="主键ID，自增" align="center" prop="id" /> -->
      <el-table-column label="昵称" align="center" prop="publisher" />
      <!-- <el-table-column label="头像" align="center" prop="avatar" /> -->
      <!-- <el-table-column label="地区" align="center" prop="region" /> -->
      <el-table-column label="内容" align="center" prop="content">
        <template slot-scope="scope">
          <el-tooltip :content="removeHtmlTags(scope.row.content)" placement="top" effect="light">
            <span class="content-text">{{ removeHtmlTags(scope.row.content) }}</span>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="发布时间" align="center" prop="publishTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.publishTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="评论数量" align="center" prop="commentCount" /> -->
      <el-table-column label="点赞数" align="center" prop="likeCount" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            @click="handleViewDetails(scope.row)"
          >查看详情</el-button>
          <el-button
            size="mini"
            type="text"
            @click="handleLike(scope.row)"
          >点赞</el-button>
          <el-button
            size="mini"
            type="text"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['campus:post:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            @click="handleDelete(scope.row)"
            v-hasPermi="['campus:post:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改帖子对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <!-- <el-form-item label="发布人昵称" prop="publisher">
          <el-input v-model="form.publisher" placeholder="请输入发布人昵称" />
        </el-form-item> -->
        <!-- <el-form-item label="发布人头像URL" prop="avatar">
          <el-input v-model="form.avatar" placeholder="请输入发布人头像URL" />
        </el-form-item> -->
        <el-form-item label="发布内容">
          <editor v-model="form.content" :min-height="192"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    
    <!-- 帖子详情对话框 -->
    <el-dialog 
      :title="'帖子详情 - #' + postDetail.id" 
      :visible.sync="detailOpen" 
      width="800px" 
      append-to-body
      class="post-detail-dialog"
      @close="handleDetailClose"
    >
      <el-card class="post-card" shadow="never">
        <div slot="header" class="post-header clearfix">
          <div class="post-author">
            <el-avatar 
              :size="30" 
              :src="baseUrl + postDetail.avatar" 
              icon="el-icon-user-solid"
              v-if="postDetail.avatar"
            ></el-avatar>
            <el-avatar 
              :size="30" 
              icon="el-icon-user-solid"
              v-else
            ></el-avatar>
            <div class="author-info">
              <span class="author-name">{{ postDetail.publisher }}</span>
              <span class="author-region" v-if="postDetail.region">
                <i class="el-icon-location-outline"></i>
                {{ postDetail.region }}
              </span>
            </div>
          </div>
          <div class="post-time">
            <i class="el-icon-time"></i>
            {{ parseTime(postDetail.publishTime, '{y}-{m}-{d} {h}:{i}:{s}') }}
          </div>
        </div>
        <div class="post-content" v-html="postDetail.content"></div>
        <div class="post-stats">
          <div class="stat-item">
            <i class="el-icon-star-off"></i>
            <span>点赞 {{ postDetail.likeCount || 0 }}</span>
          </div>
          <div class="stat-item">
            <i class="el-icon-chat-dot-round"></i>
            <span>评论 {{ postDetail.commentCount || 0 }}</span>
          </div>
        </div>
      </el-card>
      
      <div class="post-actions">
        <el-button 
          type="primary" 
          icon="el-icon-chat-line-round"
          @click="toggleCommentForm"
          size="small"
        >
          {{ showCommentForm ? '取消评论' : '发表评论' }}
        </el-button>
      </div>
      
      <el-card class="comments-card" shadow="never">
        <div slot="header" class="comments-header clearfix">
          <span>评论 ({{ commentList.length }})</span>
        </div>
        <div v-if="commentList.length === 0" class="no-comments">
          <i class="el-icon-chat-dot-round" style="font-size: 30px; margin-bottom: 10px;"></i>
          <p>暂无评论，快来抢沙发吧</p>
        </div>
        <div v-else class="comments-container">
          <div class="comments-list" :class="{ 'limited-height': !showAllComments }">
            <div v-for="comment in commentList" :key="comment.id" class="comment-item">
              <div class="comment-avatar">
                <el-avatar 
                  :size="24" 
                  :src="baseUrl + comment.avatar" 
                  icon="el-icon-user-solid"
                  v-if="comment.avatar"
                ></el-avatar>
                <el-avatar 
                  :size="24" 
                  icon="el-icon-user-solid"
                  v-else
                ></el-avatar>
              </div>
              <div class="comment-main">
                <div class="comment-header">
                  <div class="comment-author-info">
                    <span class="comment-author">{{ comment.commentator }}</span>
                    <span class="comment-region" v-if="comment.region">
                      <i class="el-icon-location-outline"></i>
                      {{ comment.region }}
                    </span>
                  </div>
                  <span class="comment-time">{{ parseTime(comment.commentTime, '{y}-{m}-{d} {h}:{i}') }}</span>
                </div>
                <div class="comment-content">{{ comment.content }}</div>
              </div>
            </div>
          </div>
          <div v-if="commentList.length > 5 && !showAllComments" class="show-more-comments">
            <el-button 
              type="text" 
              @click="showAllComments = true"
              icon="el-icon-arrow-down"
            >
              展开剩余 {{ commentList.length - 5 }} 条评论
            </el-button>
          </div>
          <div v-if="commentList.length > 5 && showAllComments" class="show-more-comments">
            <el-button 
              type="text" 
              @click="showAllComments = false"
              icon="el-icon-arrow-up"
            >
              收起评论
            </el-button>
          </div>
        </div>
        
        <!-- 添加评论表单 -->
        <div class="comment-form" v-if="showCommentForm">
          <el-form :model="commentForm" ref="commentForm" size="small">
            <el-form-item prop="content" :rules="{ required: true, message: '请输入评论内容', trigger: 'blur' }">
              <el-input 
                type="textarea" 
                :rows="3" 
                placeholder="请输入您的评论..." 
                v-model="commentForm.content"
                maxlength="200"
                show-word-limit
              />
            </el-form-item>
            <el-form-item>
              <el-button 
                type="primary" 
                size="small" 
                @click="submitComment"
                :loading="commentLoading"
              >
                提交评论
              </el-button>
              <el-button 
                size="small" 
                @click="toggleCommentForm"
              >
                取消
              </el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-card>
      
      <div slot="footer" class="dialog-footer">
        <el-button @click="detailOpen = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listPost, getPost, getPostDetail, delPost, addPost, updatePost, likePost, listPostComments, addPostComment } from "@/api/campus/post"

export default {
  name: "Post",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 帖子表格数据
      postList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        publisher: null,
        content: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        publisher: [
          { required: true, message: "发布人昵称不能为空", trigger: "blur" }
        ],
        avatar: [
          { required: true, message: "发布人头像URL不能为空", trigger: "blur" }
        ],
        content: [
          { required: true, message: "发布内容不能为空", trigger: "blur" }
        ],
      },
      // 帖子详情弹窗是否显示
      detailOpen: false,
      // 帖子详情数据
      postDetail: {},
      // 评论列表数据
      commentList: [],
      // 评论表单相关
      showCommentForm: false,
      commentLoading: false,
      commentForm: {
        content: '',
        postId: null
      },
      // 基础URL
      baseUrl: process.env.VUE_APP_BASE_API || '',
      // 控制是否显示所有评论
      showAllComments: false
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询帖子列表 */
    getList() {
      this.loading = true
      listPost(this.queryParams).then(response => {
        this.postList = response.rows || []
        this.total = response.total || 0
        this.loading = false
      }).catch(error => {
        console.error("获取帖子列表失败:", error)
        this.$modal.msgError("获取帖子列表失败")
        this.loading = false
        // 即使出错也要确保loading状态被关闭
        this.postList = []
        this.total = 0
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        publisher: null,
        avatar: null,
        region: null,
        content: null,
        publishTime: null,
        commentCount: null,
        likeCount: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加帖子"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getPost(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改帖子"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updatePost(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addPost(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除帖子编号为"' + ids + '"的数据项？').then(function() {
        return delPost(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('campus/post/export', {
        ...this.queryParams
      }, `post_${new Date().getTime()}.xlsx`)
    },
    
    /** 查看详情按钮操作 */
    handleViewDetails(row) {
      const id = row.id
      // 获取帖子详情（包含评论）
      getPostDetail(id).then(response => {
        this.postDetail = response.data || {}
        // 直接使用返回的评论列表
        this.commentList = response.data.commentList || []
        this.detailOpen = true
        // 每次打开详情时重置评论显示状态
        this.showAllComments = false
      }).catch(error => {
        console.error("获取帖子详情失败:", error)
        this.$modal.msgError("获取帖子详情失败")
      })
    },
    
    /** 点赞按钮操作 */
    handleLike(row) {
      const id = row.id
      likePost(id).then(response => {
        this.$modal.msgSuccess("点赞成功")
        // 更新列表中的点赞数
        this.getList()
      }).catch(error => {
        console.error("点赞失败:", error)
        this.$modal.msgError("点赞失败")
      })
    },
    
    /** 切换评论表单显示 */
    toggleCommentForm() {
      this.showCommentForm = !this.showCommentForm;
      if (this.showCommentForm) {
        this.commentForm.postId = this.postDetail.id;
        this.$nextTick(() => {
          this.$refs.commentForm && this.$refs.commentForm.clearValidate();
        });
      } else {
        this.commentForm.content = '';
      }
    },
    
    /** 提交评论 */
    submitComment() {
      this.$refs.commentForm.validate(valid => {
        if (valid) {
          this.commentLoading = true;
          // 这里可以设置默认的评论者信息，实际项目中可能需要从用户信息中获取
          const commentData = {
            ...this.commentForm,
            commentator: '当前用户', // 实际项目中应该从用户信息中获取
            avatar: '', // 可以设置默认头像
            region: '' // 可以设置默认地区
          };
          
          addPostComment(commentData).then(response => {
            this.$modal.msgSuccess("评论成功");
            this.toggleCommentForm();
            // 重新加载评论列表
            return listPostComments(this.postDetail.id);
          }).then(response => {
            this.commentList = response.rows || [];
            // 更新帖子的评论数
            if (this.postDetail) {
              this.postDetail.commentCount = response.rows ? response.rows.length : 0;
            }
          }).catch(error => {
            console.error("评论失败:", error)
            this.$modal.msgError("评论失败");
          }).finally(() => {
            this.commentLoading = false;
          });
        }
      });
    },
    
    /** 取消评论 */
    cancelComment() {
      this.showCommentForm = false;
      this.commentForm.content = '';
    },
    
    /** 关闭详情弹窗 */
    handleDetailClose() {
      this.cancelComment();
      // 重置评论显示状态
      this.showAllComments = false;
    },
    
    // 添加去除HTML标签的方法
    removeHtmlTags(content) {
      if (!content) return '';
      return content.replace(/<[^>]*>/g, '');
    }
  }
}
</script>

<style scoped>
.content-text {
  display: inline-block;
  max-width: 300px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  vertical-align: middle;
}

/* 帖子详情弹窗样式 */
.post-detail-dialog {
  border-radius: 8px;
}

.post-detail-dialog :deep(.el-dialog__header) {
  border-bottom: 1px solid #eee;
  padding: 15px 20px;
}

.post-card {
  margin-bottom: 20px;
  border-radius: 8px;
  border: 1px solid #ebeef5;
}

.post-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 15px;
}

.post-author {
  display: flex;
  align-items: center;
}

.author-info {
  margin-left: 10px;
}

.author-name {
  font-weight: bold;
  color: #303133;
  display: block;
}

.author-region {
  font-size: 12px;
  color: #909399;
  margin-top: 2px;
  display: flex;
  align-items: center;
}

.author-region i {
  margin-right: 3px;
}

.post-time {
  color: #909399;
  font-size: 13px;
  display: flex;
  align-items: center;
}

.post-time i {
  margin-right: 3px;
}

.comment-author-info {
  display: flex;
  align-items: center;
}

.comment-author {
  font-weight: 500;
  color: #409EFF;
  font-size: 14px;
  margin-right: 10px;
}

.comment-region {
  font-size: 12px;
  color: #909399;
  display: flex;
  align-items: center;
}

.comment-region i {
  margin-right: 3px;
}

.comment-time {
  color: #909399;
  font-size: 12px;
  display: flex;
  align-items: center;
}

.comment-time i {
  margin-right: 3px;
}

.post-stats {
  display: flex;
  padding-top: 15px;
  border-top: 1px solid #eee;
}

.stat-item {
  margin-right: 20px;
  color: #909399;
  font-size: 14px;
  display: flex;
  align-items: center;
}

.stat-item i {
  margin-right: 5px;
}

.comments-card {
  border-radius: 8px;
  border: 1px solid #ebeef5;
}

.comments-card :deep(.el-card__header) {
  padding: 12px 20px;
  border-bottom: 1px solid #eee;
}

.comments-header {
  font-weight: bold;
  color: #303133;
}

.no-comments {
  text-align: center;
  color: #909399;
  padding: 40px 20px;
}

.no-comments p {
  margin: 0;
}

.comment-item {
  display: flex;
  padding: 15px 0;
  border-bottom: 1px solid #eee;
}

.comment-item:last-child {
  border-bottom: none;
}

.comment-avatar {
  margin-right: 12px;
}

.comment-main {
  flex: 1;
}

.comment-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
}

.comment-author {
  font-weight: 500;
  color: #409EFF;
  font-size: 14px;
}

.comment-time {
  color: #909399;
  font-size: 12px;
}

.comment-content {
  color: #606266;
  line-height: 1.6;
  font-size: 14px;
  word-break: break-all;
}

.comment-actions {
  margin-top: 8px;
}

.reply-button {
  color: #409EFF;
  font-size: 12px;
}

.reply-button:hover {
  background-color: #ecf5ff;
}

.post-actions {
  text-align: right;
  padding: 10px 0;
}

.comment-form {
  padding: 15px 0 5px;
  border-top: 1px solid #eee;
  margin-top: 10px;
}

.comment-form :deep(.el-textarea__inner) {
  font-size: 14px;
}

.comment-form :deep(.el-form-item) {
  margin-bottom: 15px;
}

.comment-form :deep(.el-form-item__content) {
  display: flex;
  align-items: center;
}

.comment-form :deep(.el-form-item__error) {
  position: absolute;
  top: 100%;
  left: 0;
}

.dialog-footer {
  padding: 15px 20px;
  border-top: 1px solid #eee;
}

.comments-container {
  position: relative;
}

.comments-list {
  max-height: none;
  overflow: visible;
}

.comments-list.limited-height {
  max-height: 300px;
  overflow-y: auto;
}

.show-more-comments {
  text-align: center;
  padding: 10px 0;
  border-top: 1px solid #eee;
}

.show-more-comments :deep(.el-button) {
  font-size: 13px;
  color: #909399;
}

.show-more-comments :deep(.el-button:hover) {
  color: #409EFF;
}
</style>
